<?php

namespace App\Repository\XhApi;

use App\Libs\IdCard;
use App\Models\Orders\OrdersModel;
use App\Models\Orders\OrdersUserModel;
use App\Models\Product\GoodsModel;
use App\Models\Xh\PhonesModel;
use App\Repository\BaseRepository;
use App\Repository\UpThree\MainOrderRepostition;

class OrdersRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new OrdersModel();
        parent::__construct();
    }

    public function index($params, $page = 1, $limit = 10)
    {
        $memberId = $params['user']['id'] ?? 0;
        $ModelOrdersUser = new OrdersUserModel();
        $where = [];
        $where['where']['a.xh_member_id'] = $memberId;
//        各种类型的条件组合
//        switch ($params['type']) {
//            case 1:
//                break;
//        }
        //        先要总数
        $totalRows = 0;
        if ($page == 1) {
            $totalRows = $ModelOrdersUser->from($ModelOrdersUser->getTable() . ' AS a')->searchWhere($where)->count('a.id');
        }
        $fields = ['a.id', 'a.pay_money', 'a.pay_identity', 'a.pay_phone', 'a.post_province', 'a.post_city', 'a.post_area', 'a.post_address', 'a.author_id', 'a.author_name', 'a.sku_number',
            'b.ordersno', 'b.goods_name', 'b.goods_code', 'b.created_at', 'b.status', 'b.activat_at', 'b.first_status_at',
            'c.main_pic'];
        $rows = [];
        $ModelGoods = new GoodsModel();
        foreach ($ModelOrdersUser->from($ModelOrdersUser->getTable() . ' AS a')
                     ->leftJoin($this->model->getTable() . ' AS b', 'a.orderno', '=', 'b.ordersno')
                     ->leftJoin($ModelGoods->getTable() . ' AS c', 'b.goods_id', '=', 'c.id')
                     ->select($fields)
                     ->searchWhere($where)
                     ->page($page, $limit)
                     ->orderByDesc('a.id')
                     ->cursor() as $row) {
            $rows[] = $row;
        }
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

    public function validPhone($phone)
    {
        if (!(preg_match("/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/", $phone))) {
            return false;
        }
        return true;
    }

    // 修改自己的收货地址
    public function editAddress($params)
    {
        $ordersNo = $params['ordersno'] ?? '';
        $userId = $params['user']['id'] ?? 0;
        $ModelOrdersUser = new OrdersUserModel();
        $where = [
            'a.orderno' => $ordersNo,
            'a.xh_member_id' => $userId,
            'b.status' => 2
        ];
        $oldRow = $ModelOrdersUser->from($ModelOrdersUser->getTable() . ' AS a')
            ->leftJoin($this->model->getTable() . ' AS b', 'a.orderno', '=', 'b.ordersno')
            ->select(['a.id'])
            ->where($where)
            ->first();
        if (empty($oldRow)) {
            return $this->returnMsg(20, '订单异常');
        }
        $upArr = [
            'contact_name' => trim($params['name']),
            'contact_phone' => trim($params['phone']),
            'post_province' => trim($params['province']),
            'post_city' => trim($params['city']),
            'post_area' => trim($params['area']),
            'post_address' => trim($params['address'])
        ];
        if (!$this->validPhone($upArr['contact_phone'])) {
            return $this->returnMsg(2, '手机号码不正确');
        }
        $result = $ModelOrdersUser->where(['id' => $oldRow->id])->update($upArr);
        if (false === $result) {
            return $this->returnMsg(20, '修改异常');
        }
        return $this->returnMsg(200, '修改成功');
    }

    public function detail($memberId, $ordersno)
    {
        $ModelOrdersUser = new OrdersUserModel();
        $where = [];
        $where['where']['a.orderno'] = $ordersno;
        $where['where']['a.xh_member_id'] = $memberId;
        $fields = ['a.id', 'a.pay_money', 'a.pay_identity', 'a.pay_phone', 'a.post_province', 'a.post_city', 'a.post_area', 'a.post_address', 'a.contact_phone', 'a.contact_name', 'a.sku_number', 'a.sku_area',
            'b.ordersno', 'b.express_company', 'b.express_number', 'b.goods_name', 'b.goods_code', 'b.created_at', 'b.status', 'b.activat_at', 'b.first_status_at',
            'c.main_pic', 'c.oblong_pic'];
        $ModelGoods = new GoodsModel();
        $row = $ModelOrdersUser->from($ModelOrdersUser->getTable() . ' AS a')
            ->leftJoin($this->model->getTable() . ' AS b', 'a.orderno', '=', 'b.ordersno')
            ->leftJoin($ModelGoods->getTable() . ' AS c', 'b.goods_id', '=', 'c.id')
            ->select($fields)
            ->searchWhere($where)
            ->first();
        return $this->returnMsg(200, '查询成功', $row);
    }

    public function buy($params)
    {
        $userId = $params['user']['id'] ?? 0;
        $phonesId = $params['phonesId'] ?? 0;
        $goodsId = $params['goodsId'] ?? 0;
        // 购买的号码
        $number = $params['number'] ?? '';
        // 号码归属省
        $numberProvince = $params['numberProvince'] ?? '';
        // 号码归属市
        $numberCity = $params['numberCity'] ?? '';
        $shopId = $params['shopId'] ?? 0;
        $fromApi = $params['fromApi'] ?? 0;
        // 客户信息
        $addressId = $params['addressId'] ?? 0;
        $province = $params['province'] ?? '';
        $city = $params['city'] ?? '';
        $area = $params['area'] ?? '';
        $address = $params['address'] ?? '';
        $pay_name = $params['pay_name'] ?? '';
        $pay_phone = $params['pay_phone'] ?? '';
        $pay_identity = $params['pay_identity'] ?? '';

        if (!$this->validPhone($pay_phone)) {
            return $this->returnMsg(2, '办理人手机号码不正确');
        }
        $identityInfo = IdCard::info($pay_identity);
        if (false === $identityInfo) {
            return $this->returnMsg(2, '办理人身份证信息不正确');
        }
        $age = $identityInfo['age'] ?? '';
        $sex = $identityInfo['gender'] ?? '';
        if ($age < 18 || $age > 65) {
            return $this->returnMsg(2, '办理人年龄限制');
        }
        //下单号码的数据
        $row = [];
        $ModelGoods = new GoodsModel();
        if ($fromApi != 1) {
            $ModelPhones = new PhonesModel();
            $row = $ModelPhones->where(['id' => $phonesId, 'sale' => 0, 'status' => 0])->select(['number', 'operator', 'province', 'city', 'sale_price', 'booking'])->first();
            if (!empty($row)) {
                $numberProvince = $row['province'];
                $numberCity = $row['city'];
                // 以数据库为准,覆盖提交过来的
                $number = $row['number'];
            }
        } else {
            $fields = ['goods_code', 'goods_price AS sale_price', 'aperator AS operator'];
            $row = $ModelGoods->searchWhere(['id' => $goodsId])->select($fields)->first();
            if (!empty($row)) {
                $row['booking'] = 1;
            }
        }
        if (empty($row)) {
            return $this->returnMsg(2, '此商品已下架');
        }
        $status = 0;
        if ($row['booking'] != 1) {
            //等待支付
            $status = 2;
        }
        $money = $row['sale_price'];
        // 来源小程序
        $source = 8;
        $dist_orderno = creatOrderNums();
        $orderDatas = [
            'xh_member_id' => $userId,
            'is_api_number' => $fromApi,
            'dist_orderno' => $dist_orderno,
            'dist_id' => 0,
            'dist_name' => '5G卡号',
            'source' => $source,
            // goods_code不用,后面会查找商品
//            'goods_code' => $row['goods_code'],
            'goods_id' => $goodsId,
            //收货信息
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'address' => $address,
            'name' => $pay_name,
            'identity' => $pay_identity,
            'contact' => $pay_phone,
            'shop_id' => $shopId,
            'author_id' => '',
            'author_name' => '',
            'remark' => '',
            'dou_status' => 0,
            'douyin_id' => 0,
            'douyin_name' => '',
            'douyin_status_name' => '',
            'money' => $money,
            'status' => $status,
            'three_msg' => '',
            'sku_number' => $number,
            'sku_area' => $numberProvince . $numberCity,
            'numberProvince' => $numberProvince,
            'numberCity' => $numberCity,
            'package_name' => '',
            'created_at' => date('Y-m-d H:i:s')
        ];
        $model = new MainOrderRepostition();
        $result = $model->orderSubmit($orderDatas);
        // 下单成功后,数据库号码修改为等待支付
        if ($result['code'] == 200 && $fromApi != 1) {
            $sale = 1;
            if ($row['booking'] == 1) {
                $sale = 2;
            }
            $ModelPhones->where(['id' => $php_errormsg])->update(['sale' => $sale]);
        }
        return $result;
    }
}
